/**
 * 
 */
package org.intelligentsia.artifacts.repository.metadata.adapter;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import org.intelligentsia.artifacts.repository.metadata.SnapshotVersion;

/**
 * @author geronimo
 * 
 */
public class SnapshotVersionAdapter {

	/**
	 * @param optJSONArray
	 * @return
	 * @throws JSONException
	 */
	public static List<SnapshotVersion> read(JSONArray jsonArray) throws JSONException {
		List<SnapshotVersion> snapshotVersions = null;
		if (jsonArray != null) {
			snapshotVersions = new ArrayList<SnapshotVersion>();
			for (int index = 0; index < jsonArray.length(); index++) {
				snapshotVersions.add(read(jsonArray.getJSONObject(index)));
			}
		}
		return snapshotVersions;
	}

	/**
	 * @param snapshotVersions
	 * @return
	 * @throws JSONException
	 */
	public static JSONArray write(List<SnapshotVersion> snapshotVersions) throws JSONException {
		JSONArray array = null;
		if (snapshotVersions != null) {
			array = new JSONArray();
			for (SnapshotVersion snapshotVersion : snapshotVersions) {
				array.put(write(snapshotVersion));
			}
		}
		return array;
	}

	public static SnapshotVersion read(JSONObject jsonObject) throws JSONException {
		SnapshotVersion snapshotVersion = null;
		if (jsonObject != null) {
			snapshotVersion = new SnapshotVersion();
			snapshotVersion.setClassifier(jsonObject.optString("classifier"));
			snapshotVersion.setExtension(jsonObject.optString("extension"));
			snapshotVersion.setUpdated(jsonObject.optString("updated"));
			snapshotVersion.setVersion(jsonObject.optString("version"));
		}
		return snapshotVersion;
	}

	public static JSONObject write(SnapshotVersion snapshotVersion) throws JSONException {
		JSONObject jsonObject = null;
		if (snapshotVersion != null) {
			jsonObject = new JSONObject();
			jsonObject.putOpt("classifier", snapshotVersion.getClassifier());
			jsonObject.putOpt("extension", snapshotVersion.getExtension());
			jsonObject.putOpt("updated", snapshotVersion.getUpdated());
			jsonObject.putOpt("version", snapshotVersion.getVersion());
		}
		return jsonObject;
	}
}
